package log

import (
	"fmt"
	"gitee.com/jjawesomejj/awesome-util/echo"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	"os"
	"runtime"
	"strings"
	"time"
)

var Level map[string]string = map[string]string{
	"WARNING": "WARNING",
	"ALL":     "ALL",
	"TRACE":   "TRACE",
	"DEBUG":   "DEBUG",
	"INFO":    "INFO",
	"WARN":    "WARN",
	"ERROR":   "ERROR",
	"FATAL":   "FATAL",
	"OFF":     "OFF",
}

type FileLoger struct {
	LogPath string
}

func appendToFile(file, str string) {
	f, err := os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	if err != nil {
		fmt.Printf("Cannot open file %s!\n", file)
		return
	}
	defer f.Close()
	f.WriteString(str)
}
func getCallStrace() string {
	pc, file, line, ok := runtime.Caller(3)
	if !ok {
		fmt.Println("No caller information")
		return ""
	}

	fn := runtime.FuncForPC(pc)
	index := strings.LastIndex(fn.Name(), "/")
	namespace := ""
	packageName := ""
	if index == -1 {
		index = len(fn.Name())
	} else {
		packageName = strings.Split(fn.Name()[index+1:], ".")[0] + "/"
		namespace = fn.Name()[:index] + "/"
	}

	fileNames := strings.Split(file, "/")
	fileName := fileNames[len(fileNames)-1]
	name := namespace + packageName + fileName
	return fmt.Sprintf("%s:%d", name, line)
}

func (logger FileLoger) writeLog(level string, message string) {
	logMessage := commonhelper.Format("[{}]\t[{}]\t[{}]\t{}", time.Now().Format("2006-01-02 15:04:05"), level, getCallStrace(), message) + "\n"
	appendToFile(logger.LogPath+time.Now().Format("2006-01-02")+".log", logMessage)
	switch level {
	case "WARN":
		echo.Yellow(logMessage)
		break
	case "ERROR":
		echo.Red(logMessage)
		break
	case "Fatal":
		echo.Red(logMessage)
		break
	case "OFF":
		echo.Red(logMessage)
		break
	default:
		echo.Blue(logMessage)
		break
	}
}
func (logger FileLoger) All(message string) {
	logger.writeLog("ALL", message)
}
func (logger FileLoger) Trace(message string) {
	logger.writeLog("TRACE", message)
}
func (logger FileLoger) Debug(message string) {
	logger.writeLog("DEBUG", message)
}
func (logger FileLoger) Info(message string) {
	logger.writeLog("INFO", message)
}
func (logger FileLoger) Warn(message string) {
	logger.writeLog("WARN", message)
}
func (logger FileLoger) Error(message string) {
	logger.writeLog("ERROR", message)
}
func (logger FileLoger) Fatal(message string) {
	logger.writeLog("FATAL", message)
}
func (logger FileLoger) Off(message string) {
	logger.writeLog("OFF", message)
}
